// src/stores/modules/user/index.ts
import { defineStore } from "pinia";
import { ref, onMounted, onUnmounted } from "vue";
import {
  login as apiLogin,
  logout as apiLogout,
  verifyToken,
} from "@/api/user";
import router from "@/router";
import { ElMessage } from "element-plus";
import { usePermissionStore } from "@/stores";

export interface User {
  userId: number;
  username: string;
  nickname: string;
  roleId: number; // 用户角色ID
  email: string;
  userPhone: string;
  avatarUrl: string;
  gender: number;
  education: string;
  subjectName: string;
  studyTime: number;
  isOnline: boolean;
  studyGoal: string;
  hasSaveStudyInfo: boolean; // 是否保存了学习信息
  frontSubjectList: string[]; // 学科列表
}

export interface StudyPlan {
  userId: string;
  title: string;
  description: string;
  tasks: StudyTask[];
  createdAt: string;
  dueDate: string;
  progress: number;
}

export interface StudyTask {
  userId: string;
  title: string;
  completed: boolean;
  duration: number;
}

export const useUserStore = defineStore(
  "user",
  () => {
    //定义初始信息
    const currentUser = ref<User | null>({
      userId: 0,
      username: "",
      nickname: "",
      roleId: 0,
      email: "",
      userPhone: "",
      avatarUrl: "",
      gender: 1,
      education: "",
      subjectName: "", // 学习科目
      studyTime: 0,
      isOnline: false,
      studyGoal: "",
      hasSaveStudyInfo: false, // 是否保存了学习信息
      frontSubjectList: [], // 学科列表
    });
    //   const currentUser = ref<User | null>(null);
    const isLoggedIn = ref(false);
    const studyPlans = ref<StudyPlan[]>([]);
    const currentStudyPlan = ref<StudyPlan | null>(null);
    const token = ref<string>("");

    // 初始化从本地存储加载
    const initFromStorage = () => {
      const storedToken = localStorage.getItem("token");
      if (storedToken) {
        token.value = storedToken;
        isLoggedIn.value = true;
      }
    };

    // 登录方法
    const login = async (credentials: {
      username: string;
      password: string;
      verifyCode: string;
      codeId: string;
    }) => {
      try {
        // 登录前先清除之前用户的权限缓存
        const permissionStore = usePermissionStore();
        permissionStore.clearRoutes();

        const res = await apiLogin(credentials);
        if (res.code === 200) {
          currentUser.value = res.data;
          isLoggedIn.value = true;
          token.value = res.data.token;
          localStorage.setItem("token", token.value);

          // 设置跨标签页通信监听
          window.addEventListener("storage", handleStorageEvent);

          startTokenCheck(); // 启动定期检查
          return res;
        }
      } catch (error) {
        console.log(`登陆失败：${error}`);
      }
    };

    // 登出方法
    const logout = async () => {
      try {
        localStorage.clear(); // 清除所有本地存储
        await apiLogout(); // 调用后端接口
        clearAuth(); // 清除前端状态
        router.replace("/auth/login"); // 跳转到登录页
      } catch (error) {
        console.error("退出失败:", error);
      }
    };

    // 清理认证信息
    const clearAuth = () => {
      token.value = "";
      currentUser.value = null;
      isLoggedIn.value = false;
      localStorage.removeItem("token");
      sessionStorage.removeItem("currentRoleId"); // 清除角色ID缓存
      window.removeEventListener("storage", handleStorageEvent);

      // 清除权限相关的缓存
      const permissionStore = usePermissionStore();
      permissionStore.clearRoutes();

      ElMessage.success("已退出登录");
    };

    //定期检查
    const checkTokenValidity = async () => {
      if (!token.value) return false;
      await verifyToken();
    };
    // 登录后启动定期检查
    const startTokenCheck = () => {
      setInterval(checkTokenValidity, 30000); // 每30秒检查一次
    };

    // 处理storage事件
    const handleStorageEvent = (event: StorageEvent) => {
      if (event.key === "token-logout" && event.newValue) {
        clearAuth();
        window.location.href = "/login?message=已在其他设备登录";
      }
    };

    const updateProfile = (userData: Partial<User>) => {
      // debugger;
      if (currentUser.value) {
        Object.assign(currentUser.value, userData);
      }
    };

    const addStudyPlan = (plan: StudyPlan) => {
      studyPlans.value.push(plan);
    };

    const setCurrentStudyPlan = (plan: StudyPlan) => {
      currentStudyPlan.value = plan;
    };

    const updateStudyTask = (taskId: string, completed: boolean) => {
      if (currentStudyPlan.value) {
        const task = currentStudyPlan.value.tasks.find(
          (t) => t.userId === taskId
        );
        if (task) {
          task.completed = completed;
          const completedTasks = currentStudyPlan.value.tasks.filter(
            (t) => t.completed
          ).length;
          currentStudyPlan.value.progress =
            (completedTasks / currentStudyPlan.value.tasks.length) * 100;
        }
      }
    };

    // 初始化
    initFromStorage();

    // 移除这些生命周期钩子，因为store在路由守卫中被调用时没有组件实例
    // onMounted(() => {
    //   window.addEventListener("storage", handleStorageEvent);
    // });

    // onUnmounted(() => {
    //   window.removeEventListener("storage", handleStorageEvent);
    // });

    return {
      currentUser,
      isLoggedIn,
      studyPlans,
      currentStudyPlan,
      token,
      login,
      logout,
      updateProfile,
      addStudyPlan,
      setCurrentStudyPlan,
      updateStudyTask,
      verifyToken,
      clearAuth,
    };
  },
  {
    persist: true,
  }
);
